package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.base.service.daoimpl.BaseServiceImpl;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.UserProtectionDao;
import com.frogs.ucenter.entity.UserProtection;
import com.frogs.ucenter.v1.request.UserProtectionQueryRequest;
import com.frogs.ucenter.v1.request.UserProtectionSaveRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.service.UserProtectionService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION + "userProtectionService")
public class UserProtectionServiceImpl extends BaseServiceImpl<UserProtection> implements UserProtectionService {
	
	private static final Logger log = LoggerFactory.getLogger(UserProtectionServiceImpl.class);
	
    @Resource
    private UserProtectionDao userProtectionDao;

	@Override
	public Response saveProtection(Request request) throws Exception {
		try{
			UserProtectionSaveRequest upas = (UserProtectionSaveRequest)request;
			UserProtection up = upas.getUserProtection();
			if(null == userProtectionDao.selectById(up.getId())) {
				userProtectionDao.insert(up);
			} else {
				userProtectionDao.update(up);
			}
			return new AddResponse<UserProtection>();
		}catch(Exception e){
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response getProtection(Request request) throws Exception  {
		UserProtectionQueryRequest upqs = (UserProtectionQueryRequest)request;
		try {
			UserProtection up = userProtectionDao.selectById(upqs.getUid());
			ShowResponse<UserProtection> response = new ShowResponse<UserProtection>();
			
			response.setInfo(up);
			return response;
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}
}